package com.zdp.netty.chapter7.server;

import com.zdp.netty.chapter7.entity.SubscribeReq;
import com.zdp.netty.chapter7.entity.SubscribeResp;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @Author zhengdp
 * @Description
 */
public class SubReqServerHandler extends ChannelHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        SubscribeReq req = (SubscribeReq) msg;
        if(judge(req)) {
            System.out.println("Service accept client subscribe req : [" + req.toString() + " ]");
            ctx.writeAndFlush(buildResp(req.getSubReqId()));
        } else {
            System.err.println("Judge ERROR");
        }
    }

    private SubscribeResp buildResp(int subReqID) {
        SubscribeResp resp = new SubscribeResp();
        resp.setSubReqId(subReqID);
        resp.setRespCode(0);
        resp.setDesc("Netty book order succeed,3 days later , sent to the designated adderss");
        return resp;
    }

    private boolean judge(SubscribeReq req) {
        return "ZhengDP".equalsIgnoreCase(req.getUserName());
    }
}
